package com.chuanzhi.recyclingmall.common.advice;

import cn.hutool.json.JSONUtil;
import com.chuanzhi.recyclingmall.common.annotation.ResponseNotWrap;
import com.chuanzhi.recyclingmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 接口返回值包装
 *  只拦截controller包下面的请求时，配置指定controller
 *  @RestControllerAdvice(basePackages = "com.chuanzhi.recyclingmall.controller")
 * @author lihui
 * @version 1.0
 * @date 2023/2/19 15:56
 */
@Slf4j
@RestControllerAdvice
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    /**
     * <p> 判断哪些接口需要返回值包装，返回true才会执行beforeBodyWrite方法，返回false不执行 </p>
     *
     * @param returnType
     * @param converterType
     * @return: boolean
     * @author lihui
     * @date: 2023/2/19 15:57
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info(">>>>>>>>>>>> 判断是否需要进行返回值包装 >>>>>>>>>>>>");

        if (returnType.getDeclaringClass().isAnnotationPresent(ResponseNotWrap.class)){
            // 若在类中加了@ResponseNotWrap，则该类中的方法不做统一拦截
            return false;
        }
        if (returnType.getMethod().isAnnotationPresent(ResponseNotWrap.class)){
            // 若在方法中加了@ResponseNotWrap，则该类中的方法不做统一拦截
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result) {
            // 提供一定的灵活度，如果body已经被包装了，就不进行包装
            return body;
        }
        if (body instanceof String) {
            //解决返回值为字符串时，不能正常包装
            return JSONUtil.toJsonStr(Result.success(body));
        }
        return Result.success(body);
    }
}
